package org.rainy.gift.exception;


import org.rainy.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


/**
 * 全局异常处理类,在这个类里面可以捕获到controller层的所有的异常,在这个类里面统一做处理
 * 就不用在每个controller类中,单独try catch
 */
@RestControllerAdvice   // 在controller执行方法的前/后执行代码
public class GlobalExceptionHandler {

    /**
     * 捕获BusinessException异常的
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(e.getCode());
    }

    /**
     * 对jsr303校验的错误信息做处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        for (ObjectError allError : allErrors) {
            stringBuffer.append(allError.getDefaultMessage()+"!");
        }
        return AjaxResult.me().setSuccess(false).setMessage(stringBuffer.toString())
                .setCode(ResponseCode.RESPONSE_CODE_400.getCode());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setCode(ResponseCode.RESPONSE_CODE_500.getCode())
                .setMessage(ResponseCode.RESPONSE_CODE_500.getMessage());
    }
}
